const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const http = require('http');
const { Server } = require('socket.io');
const jwt = require('jsonwebtoken');
require('dotenv').config();

// 导入配置服务
const configService = require('./services/configService');

const authRoutes = require('./routes/auth');
const userRoutes = require('./routes/user');
const focusRoutes = require('./routes/focus');
const studyRoutes = require('./routes/study');
const friendRoutes = require('./routes/friends');
const chatRoutes = require('./routes/chat');
const aiRoutes = require('./routes/ai');
const cloudStorageRoutes = require('./routes/cloudStorage');
const careerRoutes = require('./routes/career');
const knowledgeGraphRoutes = require('./routes/knowledgeGraph');
const notificationRoutes = require('./routes/notification');
const motivationRoutes = require('./routes/motivation');
const statisticsRoutes = require('./routes/statistics');
const scheduleRoutes = require('./routes/schedule');
const configRoutes = require('./routes/config');

const { errorHandler } = require('./middleware/errorHandler');
const { authenticateToken } = require('./middleware/auth');

const app = express();
const PORT = process.env.PORT || 3002;

// 安全中间件
app.use(helmet());

// CORS配置
app.use(cors({
  origin: process.env.FRONTEND_URL || 'http://localhost:3000',
  credentials: true
}));

// 限流中间件 - 开发环境放宽限制
const limiter = rateLimit({
  windowMs: 1 * 60 * 1000, // 1分钟
  max: 1000, // 限制每个IP 1分钟内最多1000个请求（大幅放宽）
  message: '请求过于频繁，请稍后再试',
  skip: (req) => {
    // 开发环境跳过限制
    return process.env.NODE_ENV === 'development';
  }
});
app.use(limiter);

// 解析中间件
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));

// 静态文件服务 - 设置CORS头
app.use('/uploads', (req, res, next) => {
  res.header('Access-Control-Allow-Origin', process.env.FRONTEND_URL || 'http://localhost:3000');
  res.header('Access-Control-Allow-Credentials', 'true');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  res.header('Cross-Origin-Resource-Policy', 'cross-origin');
  res.header('Cross-Origin-Embedder-Policy', 'unsafe-none');
  res.header('Cross-Origin-Opener-Policy', 'same-origin-allow-popups');
  res.header('Cache-Control', 'public, max-age=31536000');
  res.header('Vary', 'Origin');
  next();
}, express.static('uploads'));

// 条件认证中间件：分享链接不需要认证
const conditionalAuth = (req, res, next) => {
  // 如果是分享链接，跳过认证
  if (req.path.startsWith('/shared/')) {
    return next();
  }
  // 其他路由需要认证
  return authenticateToken(req, res, next);
};

// 路由
app.use('/api/auth', authRoutes);
app.use('/api/user', userRoutes); // 移除认证中间件，在路由内部处理
app.use('/api/focus', authenticateToken, focusRoutes);
app.use('/api/study', authenticateToken, studyRoutes);
app.use('/api/friends', authenticateToken, friendRoutes);
app.use('/api/chat', authenticateToken, chatRoutes);
app.use('/api/ai', authenticateToken, aiRoutes);
app.use('/api/cloud-storage', cloudStorageRoutes); // 云盘存储API
app.use('/api/career', careerRoutes);
app.use('/api/knowledge-graph', authenticateToken, knowledgeGraphRoutes);
app.use('/api/notification', authenticateToken, notificationRoutes);
app.use('/api/motivation', authenticateToken, motivationRoutes);
app.use('/api/statistics', authenticateToken, statisticsRoutes);
app.use('/api/schedule', authenticateToken, scheduleRoutes);
app.use('/api/config', configRoutes);

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({ 
    status: 'OK', 
    timestamp: new Date().toISOString(),
    version: '1.0.0'
  });
});

// 测试数据库连接
app.get('/api/test-db', async (req, res) => {
  try {
    const { query } = require('./config/database');
    const result = await query('SELECT COUNT(*) as count FROM schedules');
    res.json({
      success: true,
      message: '数据库连接正常',
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '数据库连接失败',
      error: error.message
    });
  }
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({ message: '接口不存在' });
});

// 错误处理中间件
app.use(errorHandler);

// 创建HTTP服务器
const server = http.createServer(app);

// 创建Socket.IO服务器
const io = new Server(server, {
  cors: {
    origin: process.env.FRONTEND_URL || 'http://localhost:3000',
    methods: ['GET', 'POST'],
    credentials: true
  }
});

// 存储用户连接
const userSockets = new Map();

// Socket.IO连接处理
io.on('connection', (socket) => {
  console.log('用户连接:', socket.id);

  // 用户认证
  socket.on('authenticate', async (token) => {
    try {
      // 允许测试token
      if (token === 'test-token-for-websocket') {
        const userId = 'test-user';
        userSockets.set(userId, socket);
        socket.userId = userId;
        console.log(`测试用户 ${userId} 认证成功`);
        socket.emit('authenticated', { success: true, userId });
        return;
      }
      
      const jwtConfig = await configService.getJWTConfig();
      const decoded = jwt.verify(token, jwtConfig.secret);
      const userId = decoded.userId || decoded.id;
      
      // 存储用户连接
      userSockets.set(userId, socket);
      socket.userId = userId;
      
      console.log(`用户 ${userId} 认证成功`);
      socket.emit('authenticated', { success: true, userId });
    } catch (error) {
      console.error('认证失败:', error.message);
      socket.emit('authentication_error', { message: '认证失败' });
    }
  });

  // 断开连接
  socket.on('disconnect', () => {
    if (socket.userId) {
      userSockets.delete(socket.userId);
      console.log(`用户 ${socket.userId} 断开连接`);
    }
  });
});

// 导出io实例和userSockets供其他模块使用
app.set('io', io);
app.set('userSockets', userSockets);

// 启动服务器
server.listen(PORT, () => {
  console.log(`🚀 LinkMate Backend Server running on port ${PORT}`);
  console.log(`📊 Health check: http://localhost:${PORT}/api/health`);
  console.log(`🔌 WebSocket服务器已启动`);
});

module.exports = app;
